// Axios封装
import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig
} from 'axios'
import { ElMessage } from 'element-plus'
import { errMessage } from './httpStatus'

interface Result<T = any> {
  code: number
  msg: string
  data?: T
}

const config = {
  baseURL: 'http://192.168.192.195:7888', // 打包环境
  // baseURL: 'http://172.20.10.3:7888', // 打包环境
  // baseURL: '/api',
  timeout: 6000
}

class RequestHttp {
  // 定义成员变量并指定类型
  service: AxiosInstance

  public constructor(config: AxiosRequestConfig) {
    // 实例化axios
    this.service = axios.create(config)

    /**
     * 请求拦截器
     */
    this.service.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        return {
          ...config
        }
      },
      (error) => {
        return Promise.reject(error)
      }
    )

    /**
     * 响应拦截器
     */
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { code, msg } = response.data
        if (code !== 200) {
          if (msg) ElMessage.error(msg)
          else ElMessage.error(errMessage(code))
          return Promise.reject(errMessage(code))
        } else return response.data
      },
      (error) => {
        let { message } = error
        if (message == 'Network Error') {
          message = '后端接口连接异常'
        } else if (message.includes('timeout')) {
          message = '系统接口请求超时'
        } else if (message.includes('Request failed with status code')) {
          message = '系统接口' + message.substr(message.length - 3) + '异常'
        }
        ElMessage.error(message)
        return Promise.reject(error)
      }
    )
  }

  get<T>(url: string, params?: object): Promise<Result<T>> {
    return this.service.get(url, { params })
  }

  post<T>(url: string, params?: object | string): Promise<Result<T>> {
    return this.service.post(url, params)
  }

  postAvatar<T>(url: string, form: any): Promise<Result<T>> {
    return this.service.post(url, form, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }

  put<T>(url: string, params?: object | string): Promise<Result<T>> {
    return this.service.put(url, params)
  }

  delete<T>(url: string, params?: object): Promise<Result<T>> {
    return this.service.delete(url, { params })
  }
}

export default new RequestHttp(config)
